package util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class sqlSessionUtil {
    private static SqlSessionFactory sqlSessionFactory;
    static{
       try {
           sqlSessionFactory=  new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private sqlSessionUtil() {

    }
//    public static SqlSession openSession() {
//        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//        SqlSessionFactory build = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-congif.xml"));
//        SqlSession sqlSession = build.openSession();
//        return sqlSession;
//    }

    private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();
    public static SqlSession openSession(){

        SqlSession sqlSession = tl.get();
        if (sqlSession == null){
            sqlSession = sqlSessionFactory.openSession();
            tl.set(sqlSession);
        }
        return  sqlSession;
    }

    public static void close(){
        SqlSession sqlSession = tl.get();
        if (sqlSession != null){
            sqlSession.close();
            tl.remove();
        }
    }
}
